Unit-9 & 10 QB Solution

Manish Patel

Feb 4, 2024

1. Inheritance Example:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Creating instances
dog_instance = Dog("Buddy")
cat_instance = Cat("Whiskers")

# Demonstrating Inheritance
print(dog_instance.speak())  # Output: Buddy says Woof!
print(cat_instance.speak())  # Output: Whiskers says Meow!
Buddy says Woof!
Whiskers says Meow!

2. Multiple Inheritance Example:


class A:
    def method_A(self):
        return "Method from class A"

class B:
    def method_B(self):
        return "Method from class B"

class C(A, B):
    def method_C(self):
        return "Method from class C"

# Creating instance
obj_C = C()

# Demonstrating Multiple Inheritance
print(obj_C.method_A())  # Output: Method from class A
print(obj_C.method_B())  # Output: Method from class B
print(obj_C.method_C())  # Output: Method from class C
Method from class A
Method from class B
Method from class C

3. Multilevel Inheritance Example:

class Vehicle:
    def display_type(self):
        return "Vehicle"

class Car(Vehicle):
    def display_type(self):
        return "Car"

class Sedan(Car):
    def display_type(self):
        return "Sedan"

# Creating instance
sedan_instance = Sedan()

# Demonstrating Multilevel Inheritance
print(sedan_instance.display_type())  # Output: Sedan
Sedan

Hierarchy 1: Book and Derived Class

class Book:
    def __init__(self, name, n_authors, authors, publisher, ISBN, year):
        self.name = name
        self.n_authors = n_authors
        self.authors = authors
        self.publisher = publisher
        self.ISBN = ISBN
        self.year = year

    def display_info(self):
        print(f"Name: {self.name}")
        print(f"Number of Authors: {self.n_authors}")
        print(f"Authors: {', '.join(self.authors)}")
        print(f"Publisher: {self.publisher}")
        print(f"ISBN: {self.ISBN}")
        print(f"Year: {self.year}")


class DerivedBook(Book):
    def __init__(self, name, n_authors, authors, publisher, ISBN, year, course):
        super().__init__(name, n_authors, authors, publisher, ISBN, year)
        self.course = course

    def display_info(self):
        super().display_info()
        print(f"Course: {self.course}")


# Example Usage
book_instance = DerivedBook("Python Programming", 1, ["John Doe"], "Tech Publications", "978-0-123456-78-9", 2022, "Computer Science")
book_instance.display_info()
Name: Python Programming
Number of Authors: 1
Authors: John Doe
Publisher: Tech Publications
ISBN: 978-0-123456-78-9
Year: 2022
Course: Computer Science

Hierarchy 2: Staff, Teaching, and NonTeaching Classes

class Staff:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display_info(self):
        print(f"Name: {self.name}")
        print(f"Salary: ${self.salary}")


class Teaching(Staff):
    def __init__(self, name, salary, subject):
        super().__init__(name, salary)
        self.subject = subject

    def display_info(self):
        super().display_info()
        print(f"Subject: {self.subject}")


class NonTeaching(Staff):
    def __init__(self, name, salary, department):
        super().__init__(name, salary)
        self.department = department

    def display_info(self):
        super().display_info()
        print(f"Department: {self.department}")


# Example Usage
teaching_staff = Teaching("John Smith", 50000, "Mathematics")
teaching_staff.display_info()

non_teaching_staff = NonTeaching("Jane Doe", 45000, "Administration")
non_teaching_staff.display_info()
Name: John Smith
Salary: $50000
Subject: Mathematics
Name: Jane Doe
Salary: $45000
Department: Administration

Student class

Create a class called Student, having name and email as its data members and init(self, name, email) and putdata(self) as bound methods. The init function should assign the values passed as parameters to the requisite variables. The putdata function should display the data of the student. Create another class called PhDguide having name, email, and students as its data members. Here, the students variable is the list of students under the guide. The PhDguide class should have four bound methods: init, putdata, add, and remove. The init method should initialize the variables, the putdata should show the data of the guide, include the list of students, the add method should add a student to the list of students of the guide and the remove function should remove the student (if the student exists in the list of students of that guide) from the list of students.

class Student:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def putdata(self):
        print(f"Student Name: {self.name}")
        print(f"Student Email: {self.email}")


class PhDguide:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.students = []

    def putdata(self):
        print(f"Guide Name: {self.name}")
        print(f"Guide Email: {self.email}")
        print("Students under the guide:")
        for student in self.students:
            student.putdata()
            print("---")

    def add(self, student):
        if student not in self.students:
            self.students.append(student)
            print(f"{student.name} added to the guide.")

    def remove(self, student):
        if student in self.students:
            self.students.remove(student)
            print(f"{student.name} removed from the guide.")
        else:
            print(f"{student.name} is not under the guide.")


# Example Usage
student1 = Student("Alice", "alice@example.com")
student2 = Student("Bob", "bob@example.com")

guide = PhDguide("Dr. Smith", "smith@example.com")

guide.add(student1)
guide.add(student2)

guide.putdata()

guide.remove(student1)

guide.putdata()
Alice added to the guide.
Bob added to the guide.
Guide Name: Dr. Smith
Guide Email: smith@example.com
Students under the guide:
Student Name: Alice
Student Email: alice@example.com
---
Student Name: Bob
Student Email: bob@example.com
---
Alice removed from the guide.
Guide Name: Dr. Smith
Guide Email: smith@example.com
Students under the guide:
Student Name: Bob
Student Email: bob@example.com
---

invoking __init__() in case of multiple inheritance:

class A:
    def __init__(self):
        print("Initializing class A")

class B:
    def __init__(self):
        print("Initializing class B")

class C(A, B):
    def __init__(self):
        super().__init__()

# Creating an instance of class C
obj_c = C()
Initializing class A

Distance and Slope between two points in Cartesian coordinate system:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def calculate_distance(point1, point2):
    return ((point2.x - point1.x)**2 + (point2.y - point1.y)**2)**0.5

def calculate_slope(point1, point2):
    return (point2.y - point1.y) / (point2.x - point1.x)

# Example usage
point_a = Point(1, 2)
point_b = Point(4, 6)

distance = calculate_distance(point_a, point_b)
slope = calculate_slope(point_a, point_b)

print(f"Distance between points: {distance}")
print(f"Slope between points: {slope}")
Distance between points: 5.0
Slope between points: 1.3333333333333333

Overloading + and * operators for the Fraction class:

class Fraction:
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator

    def __add__(self, other):
        common_denominator = self.denominator * other.denominator
        result_numerator = (self.numerator * other.denominator) + (other.numerator * self.denominator)
        return Fraction(result_numerator, common_denominator)

    def __mul__(self, other):
        result_numerator = self.numerator * other.numerator
        result_denominator = self.denominator * other.denominator
        return Fraction(result_numerator, result_denominator)

    def __str__(self):
        return f"{self.numerator}/{self.denominator}"

# Example usage
fraction1 = Fraction(1, 2)
fraction2 = Fraction(3, 4)

sum_result = fraction1 + fraction2
product_result = fraction1 * fraction2

print(f"Sum: {sum_result}")
print(f"Product: {product_result}")
Sum: 10/8
Product: 3/8

Overloading == operator for the Student class:

class Student:
    def __init__(self, roll_no, name, age, total_marks):
        self.roll_no = roll_no
        self.name = name
        self.age = age
        self.total_marks = total_marks

    def __eq__(self, other):
        return self.total_marks == other.total_marks

    def display_info(self):
        print(f"Roll No: {self.roll_no}")
        print(f"Name: {self.name}")
        print(f"Age: {self.age}")
        print(f"Total Marks: {self.total_marks}")

# Example usage
student1 = Student(1, "Alice", 20, 85)
student2 = Student(2, "Bob", 22, 85)

if student1 == student2:
    print("Students have the same marks.")
    student1.display_info()
    student2.display_info()
else:
    print("Students do not have the same marks.")
Students have the same marks.
Roll No: 1
Name: Alice
Age: 20
Total Marks: 85
Roll No: 2
Name: Bob
Age: 22
Total Marks: 85

Overloading > and < operators for the Data class:

class Data:
    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        return self.value < other.value

    def __gt__(self, other):
        return self.value > other.value

# Example usage
data1 = Data(5)
data2 = Data(10)

if data1 > data2:
    print("data1 is greater than data2.")
elif data1 < data2:
    print("data1 is less than data2.")
else:
    print("data1 is equal to data2.")
data1 is less than data2.

Instantiating class with or without arguments:

class Data:
    def __init__(self, value=None):
        if value is not None:
            self.value = value
            print("True: Object initialized with value")
        else:
            print("False: Object initialized without value")

# Example usage
obj1 = Data(5)  # True: Object initialized with value
obj2 = Data()   # False: Object initialized without value
True: Object initialized with value
False: Object initialized without value

Create a 5X2 integer array from a range between 100 to 200 such that the difference between each element is 10

import numpy as np

arr = np.arange(100, 200, 10).reshape(5, 2)
print("5x2 Array:")
print(arr)
5x2 Array:
[[100 110]
 [120 130]
 [140 150]
 [160 170]
 [180 190]]

“Following is the provided numPy array. Return array of items by taking the third column from all rows

sampleArray = numpy.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])

import numpy as np

sampleArray = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
third_column = sampleArray[:, 2]
print("Array of items from the third column:")
print(third_column)
Array of items from the third column:
[33 66 99]

“Return array of odd rows and even columns from below numpy array

sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24], [27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])”

import numpy as np

sampleArray = np.array([[3, 6, 9, 12], [15, 18, 21, 24], [27, 30, 33, 36], [39, 42, 45, 48], [51, 54, 57, 60]])

odd_rows_even_columns = sampleArray[::2, 1::2]
print("Array of odd rows and even columns:")
print(odd_rows_even_columns)
Array of odd rows and even columns:
[[ 6 12]
 [30 36]
 [54 60]]

“Sort following NumPy array

Case 1: Sort array by the second row
Case 2: Sort the array by the second column
sampleArray = numpy.array([[34,43,73],[82,22,12],[53,94,66]])”

import numpy as np

sampleArray = np.array([[34, 43, 73], [82, 22, 12], [53, 94, 66]])

# Case 1: Sort array by the second row
sorted_by_second_row = sampleArray[:, sampleArray[1, :].argsort()]

# Case 2: Sort the array by the second column
sorted_by_second_column = sampleArray[sampleArray[:, 1].argsort()]

print("Sorted array by the second row:")
print(sorted_by_second_row)

print("\nSorted array by the second column:")
print(sorted_by_second_column)
Sorted array by the second row:
[[73 43 34]
 [12 22 82]
 [66 94 53]]

Sorted array by the second column:
[[82 22 12]
 [34 43 73]
 [53 94 66]]

Temperature program

“Write a NumPy array program to convert the values of Fahrenheit degrees into Celsius degrees. The numpy array to be considered is [0, 12, 45.21, 34, 99.91, 32] for Fahrenheit values. Values are stored into a NumPy array. After converting the following numpy array into Celsius, then sort the array and find the position of 0.0 (means where 0.0 value is located i.e. it’s index) Formula to convert value of Fahrenheit to Celsius is: C=5F/9 - 532/9 Output: Values in Fahrenheit degrees: [ 0. 12. 45.21 34. 99.91 32. ] Values in Centigrade degrees: [-17.77777778 -11.11111111 7.33888889 1.11111111 37.72777778 0. ] [-17.77777778 -11.11111111 0. 1.11111111 7.33888889 37.72777778] (array([2], dtype=int64),)”

import numpy as np

# Fahrenheit array
fahrenheit_array = np.array([0, 12, 45.21, 34, 99.91, 32])

# Convert Fahrenheit to Celsius using the given formula
celsius_array = (fahrenheit_array - 32) * 5 / 9

# Display original Fahrenheit and converted Celsius arrays
print("Values in Fahrenheit degrees:")
print(fahrenheit_array)
print("Values in Centigrade degrees:")
print(celsius_array)

# Sort the Celsius array
sorted_celsius_array = np.sort(celsius_array)

# Find the position of 0.0 in the sorted array
zero_position = np.where(sorted_celsius_array == 0.0)

# Display the sorted array and the position of 0.0
print(sorted_celsius_array)
print(zero_position)
Values in Fahrenheit degrees:
[ 0.   12.   45.21 34.   99.91 32.  ]
Values in Centigrade degrees:
[-17.77777778 -11.11111111   7.33888889   1.11111111  37.72777778
   0.        ]
[-17.77777778 -11.11111111   0.           1.11111111   7.33888889
  37.72777778]
(array([2], dtype=int64),)

Reshape program

“import numpy as np arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

Reshape arr into a 2D array and a 3D array.”

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# Reshape arr into a 2D array
arr_2d = arr.reshape(2, 6)

# Reshape arr into a 3D array
arr_3d = arr.reshape(2, 3, 2)

print("Original array:")
print(arr)

print("\nReshaped 2D array:")
print(arr_2d)

print("\nReshaped 3D array:")
print(arr_3d)
Original array:
[ 1  2  3  4  5  6  7  8  9 10 11 12]

Reshaped 2D array:
[[ 1  2  3  4  5  6]
 [ 7  8  9 10 11 12]]

Reshaped 3D array:
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]

ABTRACT CLASS PROGRAM

"Imagine you own a call center. Use the following abstract class template to create three more classes, Respondent, Manager, and Director that inherit this Employee Abstract Class.

from abc import ABC, abstractmethod

class Employee(ABC):

  @abstractmethod
  def receive_call(self):
    pass
  
  @abstractmethod
  def end_call(self):
    pass

  @abstractmethod
  def is_free(self):
    pass
  
  @abstractmethod
  def get_rank(self):
    pass
"

Create a program using the instructions given below: 1. Create a constructor in all three classes (Respondent, Manager and Director) which takes the id and name as input and initializes two additional variables, rank and free. rank should be equal to 3 for Respondent, 2 for Manager and 1 for Director. free should be a boolean variable with value True initially. (1 mark) 2. Implement rest of the methods in all three classes in the following way: (2 marks) a. receive_call(): prints the message, “call received by (name of the employee)” and sets the free variable to False. b. end_call(): prints the message, “call ended” and sets the free variable to True. c. is_free(): returns the value of the free variable d. get_rank(): returns the value of the rank variable 3. Create a class Call, with a constructor that accepts id and name of the caller and initializes a variable called assigned to False. (0.5 marks) 4. Create a class CallHandler, with three lists, respondents, managers and directors as class variables. (0.5 marks) 5. Create an add_employee() method in CallHandler class that allows you to add an employee (an object of Respondent/Manager/Director) into one of the above lists according to their rank. (1 mark) 6. Create a dispatch_call() method in CallHandler class that takes a call object as a parameter. This method should find the first available employee starting from rank 3, then rank 2 and then rank 1. If a free employee is found, call its receive_call() function and change the call’s assigned variable value to True. If no free employee is found, print the message: “Sorry! All employees are currently busy.” (2 marks) 7. Create 3 Respondent objects, 2 Manager objects and 1 Director object and add them into the list of available employees using the CallHandler’s add_employee() method. (1 mark) 8. Create a Call object and demonstrate how it is assigned to an employee. (1 mark) ”

from abc import ABC, abstractmethod

class Employee(ABC):
    def __init__(self, employee_id, name):
        self.employee_id = employee_id
        self.name = name
        self.rank = self.get_rank()
        self.free = True

    @abstractmethod
    def receive_call(self):
        pass

    @abstractmethod
    def end_call(self):
        pass

    @abstractmethod
    def is_free(self):
        pass

    @abstractmethod
    def get_rank(self):
        pass

class Respondent(Employee):
    def __init__(self, employee_id, name):
        super().__init__(employee_id, name)

    def receive_call(self):
        print(f"Call received by {self.name}")
        self.free = False

    def end_call(self):
        print("Call ended")
        self.free = True

    def is_free(self):
        return self.free

    def get_rank(self):
        return 3

class Manager(Employee):
    def __init__(self, employee_id, name):
        super().__init__(employee_id, name)

    def receive_call(self):
        print(f"Call received by {self.name}")
        self.free = False

    def end_call(self):
        print("Call ended")
        self.free = True

    def is_free(self):
        return self.free

    def get_rank(self):
        return 2

class Director(Employee):
    def __init__(self, employee_id, name):
        super().__init__(employee_id, name)

    def receive_call(self):
        print(f"Call received by {self.name}")
        self.free = False

    def end_call(self):
        print("Call ended")
        self.free = True

    def is_free(self):
        return self.free

    def get_rank(self):
        return 1

class Call:
    def __init__(self, caller_id, caller_name):
        self.caller_id = caller_id
        self.caller_name = caller_name
        self.assigned = False

class CallHandler:
    respondents = []
    managers = []
    directors = []

    def add_employee(self, employee):
        if employee.get_rank() == 3:
            self.respondents.append(employee)
        elif employee.get_rank() == 2:
            self.managers.append(employee)
        elif employee.get_rank() == 1:
            self.directors.append(employee)

    def dispatch_call(self, call):
        for employee in self.respondents + self.managers + self.directors:
            if employee.is_free():
                employee.receive_call()
                call.assigned = True
                break
        else:
            print("Sorry! All employees are currently busy.")

# Step 7: Creating employees
respondent1 = Respondent(1, "Respondent1")
respondent2 = Respondent(2, "Respondent2")
respondent3 = Respondent(3, "Respondent3")

manager1 = Manager(4, "Manager1")
manager2 = Manager(5, "Manager2")

director1 = Director(6, "Director1")

# Adding employees to the CallHandler
call_handler = CallHandler()
call_handler.add_employee(respondent1)
call_handler.add_employee(respondent2)
call_handler.add_employee(respondent3)
call_handler.add_employee(manager1)
call_handler.add_employee(manager2)
call_handler.add_employee(director1)

# Step 8: Creating a Call object and demonstrating call dispatch
call1 = Call(101, "John Doe")
call_handler.dispatch_call(call1)
Call received by Respondent1

Write a python program to create a Bus child class that inherits from the Vehicle class.

In Vehicle class vehicle name, mileage and seatingcapacity as its data member. The default fare charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will become the final amount = total fare + 10% of the total fare.

Sample Output: The bus seating capacity is 50. so, the final fare amount should be 5000+500=5500.

The car seating capacity is 5. so, the final fare amount should be 500.”

class Vehicle:
    def __init__(self, name, mileage, seating_capacity):
        self.name = name
        self.mileage = mileage
        self.seating_capacity = seating_capacity

    def calculate_fare(self):
        return self.seating_capacity * 100

class Bus(Vehicle):
    def __init__(self, name, mileage, seating_capacity):
        super().__init__(name, mileage, seating_capacity)

    def calculate_fare(self):
        base_fare = super().calculate_fare()
        maintenance_charge = 0.1 * base_fare
        final_fare = base_fare + maintenance_charge
        return final_fare

# Example usage:
bus_instance = Bus("Bus", 10, 50)
car_instance = Vehicle("Car", 20, 5)

bus_fare = bus_instance.calculate_fare()
car_fare = car_instance.calculate_fare()

print(f"The bus seating capacity is {bus_instance.seating_capacity}. "
      f"So, the final fare amount should be {bus_fare}.")

print(f"The car seating capacity is {car_instance.seating_capacity}. "
      f"So, the final fare amount should be {car_fare}.")
The bus seating capacity is 50. So, the final fare amount should be 5500.0.
The car seating capacity is 5. So, the final fare amount should be 500.

Create an abstract class named Shape.

Create an abstract method named calculate_area for the Shape class. Create Two Classes named Rectangle and Circle which inherit Shape class. Create calculate_area method in Rectangle class. It should return the area of the rectangle object. (area of rectangle = (length * breadth)) Create calculate_area method in Circle class. It should return the area of the circle object. (area of circle =πr^2)) Create objects of Rectangle and Circle class. The python Program Should also check whether the area of one Rectangle object is greater than another rectangle object by overloading > operator. Execute the method resolution order of the Circle class. ”

from abc import ABC, abstractmethod
import math

class Shape(ABC):
    @abstractmethod
    def calculate_area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def calculate_area(self):
        return self.length * self.breadth

    def __gt__(self, other):
        return self.calculate_area() > other.calculate_area()

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return math.pi * (self.radius ** 2)

# Creating objects of Rectangle and Circle class
rectangle1 = Rectangle(5, 10)
rectangle2 = Rectangle(3, 8)

circle = Circle(7)

# Checking whether the area of one Rectangle object is greater than another
if rectangle1 > rectangle2:
    print("Area of rectangle1 is greater than rectangle2.")
else:
    print("Area of rectangle2 is greater than rectangle1.")

# Printing the method resolution order of the Circle class
print(f"Method Resolution Order for Circle class: {Circle.mro()}")
Area of rectangle1 is greater than rectangle2.
Method Resolution Order for Circle class: [<class '__main__.Circle'>, <class '__main__.Shape'>, <class 'abc.ABC'>, <class 'object'>]

Write a python program to demonstrate the use of super() method to call the method of base class.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def speak(self):
        super().speak()  # Calling the speak method of the base class
        print(f"{self.name} barks loudly")

# Create an instance of the Dog class
dog_instance = Dog("Buddy", "Labrador")

# Call the speak method of the Dog class
dog_instance.speak()
Buddy makes a sound
Buddy barks loudly

Create a class called Matrix containing constructor that initialized the number of rows and number of columns of a new Matrix object.

The Matrix class has methods for each of the following: 1. get the number of rows 2. get the number of columns 3. set the elements of the matrix at given position (i,j) 4. adding two matrices. If the matrices are not addable, “ Matrices cannot be added” will be displayed.(Overload the addition operation to perform this) 5. Multiplying the two matrices. If the matrices are not multiplied, “ Matrices cannot be multiplied” will be displayed.(Overload the addition operation to perform this) ”

class Matrix:
    def __init__(self, rows, columns):
        self.rows = rows
        self.columns = columns
        self.matrix = [[0 for _ in range(columns)] for _ in range(rows)]

    def get_rows(self):
        return self.rows

    def get_columns(self):
        return self.columns

    def set_element(self, i, j, value):
        if 0 <= i < self.rows and 0 <= j < self.columns:
            self.matrix[i][j] = value
        else:
            print("Invalid position. Cannot set element.")

    def add_matrices(self, other_matrix):
        if self.rows == other_matrix.get_rows() and self.columns == other_matrix.get_columns():
            result_matrix = Matrix(self.rows, self.columns)
            for i in range(self.rows):
                for j in range(self.columns):
                    result_matrix.set_element(i, j, self.matrix[i][j] + other_matrix.matrix[i][j])
            return result_matrix
        else:
            print("Matrices cannot be added.")

    def multiply_matrices(self, other_matrix):
        if self.columns == other_matrix.get_rows():
            result_matrix = Matrix(self.rows, other_matrix.get_columns())
            for i in range(self.rows):
                for j in range(other_matrix.get_columns()):
                    result = 0
                    for k in range(self.columns):
                        result += self.matrix[i][k] * other_matrix.matrix[k][j]
                    result_matrix.set_element(i, j, result)
            return result_matrix
        else:
            print("Matrices cannot be multiplied.")

    def __str__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.matrix])

# Example usage:
matrix1 = Matrix(2, 3)
matrix2 = Matrix(3, 2)

matrix1.set_element(0, 0, 1)
matrix1.set_element(0, 1, 2)
matrix1.set_element(0, 2, 3)
matrix1.set_element(1, 0, 4)
matrix1.set_element(1, 1, 5)
matrix1.set_element(1, 2, 6)

matrix2.set_element(0, 0, 7)
matrix2.set_element(0, 1, 8)
matrix2.set_element(1, 0, 9)
matrix2.set_element(1, 1, 10)
matrix2.set_element(2, 0, 11)
matrix2.set_element(2, 1, 12)

print("Matrix 1:")
print(matrix1)

print("\nMatrix 2:")
print(matrix2)

result_addition = matrix1.add_matrices(matrix2)
print("\nMatrix Addition:")
print(result_addition)

result_multiplication = matrix1.multiply_matrices(matrix2)
print("\nMatrix Multiplication:")
print(result_multiplication)
Matrix 1:
1 2 3
4 5 6

Matrix 2:
7 8
9 10
11 12
Matrices cannot be added.

Matrix Addition:
None

Matrix Multiplication:
58 64
139 154

“Find the MRO of class Z of below program:

class A: pass
class B: pass
class C: pass
class D:pass
class E:pass
class K1(C,A,B): pass
class K3(A,D): pass
class K2(B,D,E): pass
class Z( K1,K3,K2): pass"

class A: 
    pass
class B: 
    pass
class C: 
    pass
class D:
    pass
class E:
    pass
class K1(C,A,B): 
    pass
class K3(A,D): 
    pass
class K2(B,D,E): 
    pass
class Z( K1,K3,K2): 
    pass

print(Z.mro())
[<class '__main__.Z'>, <class '__main__.K1'>, <class '__main__.C'>, <class '__main__.K3'>, <class '__main__.A'>, <class '__main__.K2'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.E'>, <class 'object'>]

“Write a Python Program to Find the Net Salary of Employee using Inheritance.

Create three Class Employee, Perks, NetSalary. Make an Employee class as an abstract class. Employee class should have methods for following tasks. - To get employee details like employee id, name and salary from user. - To print the Employee details. - return Salary. - An abstract method emp_id. Perks class should have methods for following tasks. - To calculate DA, HRA, PF. - To print the individual and total of Perks (DA+HRA-PF). Netsalary class should have methods for following tasks. - Calculate the total Salary after Perks. - Print employee detail also prints DA, HRA, PF and net salary.

Note 1: DA-35%, HRA-17%, PF-12% Note 2: It is compulsory to create objects and demonstrating the methods with Correct output. Example: Employee ID: 1 Employee Name: John Employee Basic Salary: 25000 DA: 8750.0 HRA: 4250.0 PF: 3000.0 Total Salary: 35000.0”

from abc import ABC, abstractmethod

class Employee(ABC):
    def __init__(self):
        self.emp_id = None
        self.name = None
        self.salary = None

    def get_employee_details(self):
        self.emp_id = int(input("Enter Employee ID: "))
        self.name = input("Enter Employee Name: ")
        self.salary = float(input("Enter Employee Basic Salary: "))

    @abstractmethod
    def emp_id(self):
        pass

    def print_employee_details(self):
        print("Employee ID:", self.emp_id)
        print("Employee Name:", self.name)
        print("Employee Basic Salary:", self.salary)

    def get_salary(self):
        return self.salary

class Perks(Employee):
    def __init__(self):
        super().__init__()

    def calculate_perks(self):
        self.da = 0.35 * self.salary
        self.hra = 0.17 * self.salary
        self.pf = 0.12 * self.salary

    def print_perks(self):
        print("DA:", self.da)
        print("HRA:", self.hra)
        print("PF:", self.pf)
        print("Total Perks:", self.da + self.hra - self.pf)

class NetSalary(Perks):
    def __init__(self):
        super().__init__()

    def calculate_net_salary(self):
        self.net_salary = self.salary + self.da + self.hra - self.pf

    def print_net_salary(self):
        self.print_employee_details()
        self.print_perks()
        print("Total Salary:", self.net_salary)

    def emp_id(self):
        # Implement the emp_id method here
        pass

# Create an object of NetSalary class and demonstrate its methods
employee = NetSalary()
employee.get_employee_details()
employee.calculate_perks()
employee.calculate_net_salary()
employee.print_net_salary()
Enter Employee ID: 1
Enter Employee Name: John
Enter Employee Basic Salary: 25000
Employee ID: 1
Employee Name: John
Employee Basic Salary: 25000.0
DA: 8750.0
HRA: 4250.0
PF: 3000.0
Total Perks: 10000.0
Total Salary: 35000.0

UNIT 10 MATPLOTLIB LIBRARY

These cost categories applied to a $9.00 microcontroller:

Engineering $1.35
Manufacturing $3.60
Sales $2.25
Profit $1.80
Create a  pie chart will show the cost breakdown as different sized pieces. 
import matplotlib.pyplot as plt

# Cost breakdown
cost_categories = ['Engineering', 'Manufacturing', 'Sales', 'Profit']
cost_values = [1.35, 3.60, 2.25, 1.80]

# Create a pie chart
plt.figure(figsize=(8, 8))
plt.pie(cost_values, labels=cost_categories, autopct='%1.1f%%', startangle=140, colors=['skyblue', 'lightgreen', 'lightcoral', 'gold'])
plt.title('Cost Breakdown for a $9.00 Microcontroller')
plt.show()

These cost categories applied to a $9.00 microcontroller:

“Here is how many students got each grade in the recent test:

A- 4, B-12, C-10, D-2. Plot a pie chart for the student grades in the recent chart with different colors for each student grades and create a wedge for D. Also put a chart title as student’s grade history.”

import matplotlib.pyplot as plt

# Student grades data
grades = ['A', 'B', 'C', 'D']
students_count = [4, 12, 10, 2]

# Colors for each grade
colors = ['lightgreen', 'skyblue', 'lightcoral', 'gold']

# Create a pie chart
plt.figure(figsize=(8, 8))
plt.pie(students_count, labels=grades, autopct='%1.1f%%', startangle=140, colors=colors, explode=(0, 0, 0, 0.1))
plt.title("Student's Grade History")

# Display the pie chart
plt.show()

“Here is how many students got each grade in the recent test:

Imagine you survey your friends to find the kind of movie they like best:

Comedy- 4, Action -5, Romance - 6, Drama -1, SciFi - 4. Plot a pie chart for the above survey and use different color for each analysis and create a wedge for action movies. Also put as chart title as “Survey analysis of movie”

import matplotlib.pyplot as plt

# Movie preferences data
genres = ['Comedy', 'Action', 'Romance', 'Drama', 'SciFi']
counts = [4, 5, 6, 1, 4]

# Colors for each genre
colors = ['skyblue', 'lightcoral', 'lightgreen', 'gold', 'lightpink']

# Create a pie chart
plt.figure(figsize=(8, 8))
explode = (0, 0.1, 0, 0, 0)  # Explode the Action wedge
plt.pie(counts, labels=genres, autopct='%1.1f%%', startangle=140, colors=colors, explode=explode)
plt.title("Survey Analysis of Movie Preferences")

# Display the pie chart
plt.show()

Create a Pie Chart using Python Program

for the popularity data of different programming languages and displayed it as a pie chart using the Matplotlib Python library. For Python- 29, Java – 19, Javascript – 8, C# - 7, PHP – 6, C,C++ - 5, R – 3. Create an exploded view of python and show the % of each programming language in Pie Chart.

import matplotlib.pyplot as plt

# Programming languages data
languages = ['Python', 'Java', 'Javascript', 'C#', 'PHP', 'C/C++', 'R']
popularity = [29, 19, 8, 7, 6, 5, 3]

# Explode Python wedge
explode = [0.1 if lang == 'Python' else 0 for lang in languages]

# Create a pie chart
plt.figure(figsize=(8, 8))
plt.pie(popularity, labels=languages, autopct='%1.1f%%', startangle=140, explode=explode, colors=plt.cm.Paired.colors)
plt.title("Popularity of Programming Languages")

# Display the pie chart
plt.show()

“Write a python program to create a bar plot of

course v/s no. of students using the following dictionary with appropriate labels for X and Y axes and colour of the bars green. Data={‘C’:20,’C++’:15,’Java’:30,’Python’:35}”

import matplotlib.pyplot as plt

# Data
data = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35}

# Extracting labels and values
courses = list(data.keys())
students = list(data.values())

# Create a bar plot
plt.bar(courses, students, color='green')
plt.xlabel('Courses')
plt.ylabel('Number of Students')
plt.title('Number of Students per Course')

# Display the bar plot
plt.show()

“Create a bar chart for the following dataset: Country = [‘USA’,‘Canada’,‘Germany’,‘UK’,‘France’]

GDP_Per_Capita = [45000,42000,52000,49000,47000]. Also plot title, X-Axis, Y-Axis, different color for each country and the grid should be visible”

import matplotlib.pyplot as plt

# Dataset
countries = ['USA', 'Canada', 'Germany', 'UK', 'France']
gdp_per_capita = [45000, 42000, 52000, 49000, 47000]

# Create a bar chart
plt.bar(countries, gdp_per_capita, color=['blue', 'orange', 'green', 'red', 'purple'])
plt.xlabel('Country')
plt.ylabel('GDP Per Capita')
plt.title('GDP Per Capita by Country')
plt.grid(True)

# Display the bar chart
plt.show()

A Bar Chart

to display employee id numbers on X-axis and their salaries as Y-axis in the form of a bar graph for two departments of a company. There are two departments like sales department and purchase department. For sales department their id’s and salaries are mentioned as : x= [1001,1003,1006,1007,1009,1011] and y= [10000, 23000.50,18000.33,16500.5,12000.75, 9999.99] and for purchase department their id’s and salaries are mentioned as: x=[100̣2,1004,1010,1008,1014,1015] and y=[ 5000,6000,4500.5,12000,9000,10000]. Make the chart title as “Microsoft Inc.”, x-axis as emplyee id and Y axis as Salary. Use different colors for sales and purchase department.

import matplotlib.pyplot as plt

# Sales Department data
sales_ids = [1001, 1003, 1006, 1007, 1009, 1011]
sales_salaries = [10000, 23000.50, 18000.33, 16500.5, 12000.75, 9999.99]

# Purchase Department data
purchase_ids = [1002, 1004, 1010, 1008, 1014, 1015]
purchase_salaries = [5000, 6000, 4500.5, 12000, 9000, 10000]

# Create a bar chart
plt.bar(sales_ids, sales_salaries, color='blue', label='Sales Department', alpha=0.7)
plt.bar(purchase_ids, purchase_salaries, color='green', label='Purchase Department', alpha=0.7)

plt.xlabel('Employee ID')
plt.ylabel('Salary')
plt.title('Microsoft Inc.')
plt.legend()
plt.grid(True)

# Display the bar chart
plt.show()

Subplots of Bar Graphs for Two Dictionaries

import matplotlib.pyplot as plt

# Data
D1 = {"aryan": 66, "bob": 70, "jack": 66, "seema": 34}
D2 = {"joy": 45, "sid": 85, "hina": 90}

# Create subplots
fig, axs = plt.subplots(2, 1, figsize=(8, 8))

# Bar plot for D1
axs[0].bar(D1.keys(), D1.values(), color='blue')
axs[0].set_title('Department 1')

# Bar plot for D2
axs[1].bar(D2.keys(), D2.values(), color='green')
axs[1].set_title('Department 2')

# Set common title for subplots
fig.suptitle('BAR PLOT')

# Display the subplots
plt.show()

Histogram for Employee Ages

import matplotlib.pyplot as plt

# Data
emp_ages = [22, 45, 30, 59, 58, 56, 57, 45, 43, 43, 50, 40, 34, 33, 25, 19]
bins = [0, 10, 20, 30, 40, 50, 60]

# Create a histogram
plt.hist(emp_ages, bins=bins, color='cyan')
plt.xlabel('Employee Ages')
plt.ylabel('Number of Employees')
plt.title('Oracle Corp')

# Display the histogram
plt.show()

Histogram for Employee Ages

Histogram for Customer Wait Times

import matplotlib.pyplot as plt

# Data
wait_times = [43.1, 35.6, 37.6, 36.5, 45.3, 43.5, 40.3, 50.2, 47.3, 31.2, 42.2, 45.5, 30.3, 31.4, 35.6, 45.2, 54.1, 45.6, 36.5, 43.1]

# Create a histogram
plt.hist(wait_times, bins=10, color='lightblue', edgecolor='black')
plt.xlabel('Wait Times (seconds)')
plt.ylabel('Number of Customers')
plt.title('Customer Wait Times')

# Display the histogram
plt.show()

Histogram for Customer Wait Times

Histogram for Tree Heights

import matplotlib.pyplot as plt

# Data
tree_heights = [61, 63, 64, 66, 68, 69, 71, 71.5, 72, 72.5, 73, 73.5, 74, 74.5, 76, 76.2, 76.5, 77, 77.5, 78, 78.5, 79, 79.2, 80, 81, 82, 83, 84, 85, 87]

# Create a histogram
plt.hist(tree_heights, bins=15, color='green', edgecolor='black')
plt.xlabel('Tree Heights (inches)')
plt.ylabel('Number of Trees')
plt.title('Height of Trees', fontsize=20)

# Display the histogram
plt.show()

Histogram for Tree Heights

Line Chart for Company Profits

import matplotlib.pyplot as plt

# Data
years = [2012, 2013, 2014, 2015, 2016, 2017]
profits = [9, 10, 10.5, 8.8, 10.9, 9.75]

# Create a line chart
plt.plot(years, profits, linestyle='--', marker='o', color='blue')
plt.xlabel('Years')
plt.ylabel('Profits (in Millions)')
plt.title('XYZ Company')

# Display the line chart
plt.show()

Line Chart for Company Profits

Scatter Plot for Animal Counts

import matplotlib.pyplot as plt

# Data
animals = ['Zebra', 'Lions', 'Monkeys', 'Elephants', 'Ostriches']
counts = [25, 5, 50, 10, 20]

# Create a scatter plot
plt.scatter(animals, counts, color='purple')
plt.xlabel('Type of Animal')
plt.ylabel('Number')
plt.title('Animal Counts')

# Display the scatter plot
plt.show()

Scatter Plot for Animal Counts

Scatter Plot for Discounts and Sales

import matplotlib.pyplot as plt

# Data
discounts = [10, 20, 30, 40, 50]
sales = [1000, 1500, 1200, 1800, 2000]

# Create a scatter plot
plt.scatter(discounts, sales, color='orange')
plt.xlabel('Discount Offered (%)')
plt.ylabel('Sales (Rupees)')
plt.title('Discount vs. Sales')

# Display the scatter plot
plt.show()

Scatter Plot for Discounts and Sales

Subplots for Student Marks

import matplotlib.pyplot as plt

# Marks data (sample data)
subjects = ['Digital Electronics', 'Probability and Stochastics', 'Python', 'Full Stack Development', 'IELTS (Reading)', 'Data Structure']
marks = [
    [90, 78, 85, 92, 88],
    [70, 82, 75, 88, 95],
    [85, 90, 92, 78, 80],
    [78, 85, 80, 92, 88],
    [95, 92, 88, 80, 85],
    [80, 75, 85, 92, 78]
]

# Create subplots
fig, axs = plt.subplots(2, 3, figsize=(15, 8))
fig.suptitle('Student Marks')

# Plot for each subject
for i in range(len(subjects)):
    row, col = divmod(i, 3)
    axs[row, col].hist(marks[i], bins=10, color='lightgreen', edgecolor='black')
    axs[row, col].set_title(subjects[i])
    axs[row, col].set_xlabel('Marks')
    axs[row, col].set_ylabel('Number of Students')

# Display the subplots
plt.tight_layout(h_pad=2.0)  # Increase the vertical spacing between the plots

plt.show()

Subplots for Student Marks

Scatter Plot for Mathematics and Science Marks

import matplotlib.pyplot as plt

# Data
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Create a scatter plot
plt.scatter(marks_range, math_marks, label='Mathematics', color='blue')
plt.scatter(marks_range, science_marks, label='Science', color='orange')

# Add labels and title
plt.xlabel('Marks Range')
plt.ylabel('Marks')
plt.title('Mathematics vs Science Marks')
plt.legend()

# Display the scatter plot
plt.show()

Scatter Plot for Mathematics and Science Marks

“Draw multiple plots in one figure using subplot function. The multiple plots include below according to order:

  1. Plot a scatter plot with following data: x = [5,7,8,7,2,17,2,9,4,11,12,9,6] y = [99,86,87,88,111,86,103,87,94,78,77,85,86] The x axis represents the age of car while y axis represents the speed of car. The title of the graph should be age v/s speed of car. Also in graph there should be x and y labels. The marker used should be star. The marker color should be green. The marker size should be 60. (Entire Scatter plot 2 marks)
  2. Plot a horizontal bar with following data: x=[““A”“,”“B”“,”“C”“,”“D””] y=[3, 8, 1, 10] The x axis represents the name of car while y axis represents the selling of car. The title of the graph should be name v/s selling of car. Also in graph there should be x and y label. The horizontal bar chart’s height should be 0.1. The color of bar should be yellow. (Entire bar plot 2 marks)
  3. Plot a histogram with following data: data=[1,3,3,3,3,9,9,5,4,4,8,8,8,6,7] bins=4, the title of the graph should be histogram of cars. The orientation should be vertical. The color of plot should be violet (Entire histogram plot 2 marks)
  4. Plot a pie with following data: y=[35,25,25,15] mylabels=[‘Apple’,‘Bananas’,‘Cherries’,‘Dates’] The title of the graph should be pie chart. The exploded view should be shown with 0.2 value for ‘Apple’ (Entire pie chart of 2 marks) Also need to provide a superior title to the subplot prepared i.e ‘My Subplot for cars’(0.5 marks) and subplot preparation (0.5 mark) For clear visualization can use the following syntax after importing matplotlib plt.figure(figsize=(10,10))

import matplotlib.pyplot as plt

# Data for scatter plot
x_scatter = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y_scatter = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

# Data for horizontal bar plot
x_bar = ["A", "B", "C", "D"]
y_bar = [3, 8, 1, 10]

# Data for histogram
data_hist = [1, 3, 3, 3, 3, 9, 9, 5, 4, 4, 8, 8, 8, 6, 7]
bins_hist = 4

# Data for pie chart
y_pie = [35, 25, 25, 15]
labels_pie = ['Apple', 'Bananas', 'Cherries', 'Dates']

# Subplot preparation
plt.figure(figsize=(10, 10))

# Subplot 1: Scatter Plot
plt.subplot(2, 2, 1)
plt.scatter(x_scatter, y_scatter, marker='*', color='green', s=60)
plt.title('Age vs Speed of Car')
plt.xlabel('Age of Car')
plt.ylabel('Speed of Car')

# Subplot 2: Horizontal Bar Plot
plt.subplot(2, 2, 2)
plt.barh(x_bar, y_bar, height=0.1, color='yellow')
plt.title('Name vs Selling of Car')
plt.xlabel('Name of Car')
plt.ylabel('Selling of Car')

# Subplot 3: Histogram
plt.subplot(2, 2, 3)
plt.hist(data_hist, bins=bins_hist, orientation='vertical', color='violet')
plt.title('Histogram of Cars')
plt.xlabel('Cars')
plt.ylabel('Frequency')

# Subplot 4: Pie Chart
plt.subplot(2, 2, 4)
plt.pie(y_pie, labels=labels_pie, autopct='%1.1f%%', explode=[0.2, 0, 0, 0], startangle=90)
plt.title('Pie Chart')

# Superior Title
plt.suptitle('My Subplot for Cars')

# Show the subplot
plt.show()

“There is an array of scores of 5 Batsmen in 4 T20 Matches. Which is given below.

Scores= [[13, 10, 9, 33], [63, 46, 90, 42], [39, 76, 13, 29], [82, 9, 29, 78], [67, 61, 59, 36]] Further you are asked to perform below tasks. (i). Add scores of every batsman of 5th Match given below in the same array and print the array. Match_6= [41, 87, 72, 36, 92] (ii). Add two new batsmen’s scores in respective 5 T20 Matches in the array created in task (i) above and print the array. Batsman_6= [77, 83, 98, 95, 89] Batsman_7= [92, 71, 52, 61, 53] (iii). Add extra column with sum of all 5 T20 Matches’ scores of each batsman in the array created in task (ii) and print the final array. Note: Use Numpy module for all the Arrays given above. “Using the final array created in task(iii) above, generate graphs mentioned below: (a). Make a line chart of Total Scores of each batsman which is stored in last column of final array v/s No. of Batsman. Use dashed line in graph, with black color. Give label on x-axis as “No. of Batsman” and label on y-axis as “Scores”. Give title to the chart as “Leader Board” with bold fonts. (b). Make one Bar chart of scores of Batsman_1 and Batsman_2 for all 5 T20 matches. Give color for bars of Batsman_1 as Purple and for Batsman_2 Dark red. Also show required legend in bar chart. (c). Make a pie chart of Total Scores of each batsman which is stored in last column of final array. Show the pie chart with exploded view of all pieces with 0.1 amount. Also display percentage in the pie chart. Also show required legend for pie chart. Note: Passing the values using numpy Array Slicing from array created in task(iii) for creating graphs above is compulsory.”

import numpy as np
import matplotlib.pyplot as plt

# Task (i)
Scores = np.array([[13, 10, 9, 33],
                   [63, 46, 90, 42],
                   [39, 76, 13, 29],
                   [82, 9, 29, 78],
                   [67, 61, 59, 36]])

Match_6 = np.array([41, 87, 72, 36, 92])
# Append Match_6 as a new column to Scores
Scores = np.append(Scores, Match_6.reshape(-1, 1), axis=1)  # Append along columns (axis=1)

print("Task (i):")
print(Scores)
print()


# Task (ii)
Batsman_6 = np.array([77, 83, 98, 95, 89])
Batsman_7 = np.array([92, 71, 52, 61, 53])

Scores = np.concatenate((Scores, Batsman_6.reshape(-1, 1), Batsman_7.reshape(-1, 1)), axis=1)

print("Task (ii):")
print(Scores)
print()

# Task (iii)
Total_Scores = np.sum(Scores[:, :-2], axis=1)
Scores = np.concatenate((Scores, Total_Scores.reshape(-1, 1)), axis=1)

print("Task (iii):")
print(Scores)
print()

# Graphs
# (a) Line chart
batsman_numbers = np.arange(1, Scores.shape[0] + 1)  # Adjusted for the number of batsmen
total_scores = Scores[:, -1]

plt.figure(figsize=(10, 6))
plt.plot(batsman_numbers, total_scores, linestyle='dashed', color='black')
plt.xlabel('No. of Batsman')
plt.ylabel('Scores')
plt.title('Leader Board', fontweight='bold')
plt.show()


# (b) Bar chart
batsman_1_scores = Scores[:, -4]
batsman_2_scores = Scores[:, -3]

plt.figure(figsize=(10, 6))
plt.bar(batsman_numbers - 0.2, batsman_1_scores, width=0.4, color='purple', label='Batsman_1')
plt.bar(batsman_numbers + 0.2, batsman_2_scores, width=0.4, color='darkred', label='Batsman_2')
plt.xlabel('T20 Matches')
plt.ylabel('Scores')
plt.legend()
plt.show()

# (c) Pie chart
labels = [f'Batsman_{i}' for i in range(1, Scores.shape[1] - 2)]  # Adjusted for the number of batsmen
explode = [0.1] * len(labels)

plt.figure(figsize=(8, 8))
plt.pie(total_scores, labels=labels, explode=explode, autopct='%1.1f%%', startangle=90)
plt.title('Total Scores Distribution')
plt.legend(labels, loc='upper left')
plt.show()

Task (i):
[[13 10  9 33 41]
 [63 46 90 42 87]
 [39 76 13 29 72]
 [82  9 29 78 36]
 [67 61 59 36 92]]

Task (ii):
[[13 10  9 33 41 77 92]
 [63 46 90 42 87 83 71]
 [39 76 13 29 72 98 52]
 [82  9 29 78 36 95 61]
 [67 61 59 36 92 89 53]]

Task (iii):
[[ 13  10   9  33  41  77  92 106]
 [ 63  46  90  42  87  83  71 328]
 [ 39  76  13  29  72  98  52 229]
 [ 82   9  29  78  36  95  61 234]
 [ 67  61  59  36  92  89  53 315]]

“Write a program to build 6 graphs(3 row and 2 column) using subplot function for given data:

Subplot 1: Draw a line from (5,5) to (10,17) to (25,25) to (60,40) to (80,30) with suitable label in the x axis, y axis and a title. Line color should be green. Line style should be dotted. Marker should be diamond. Subplot 2: Write a Python program to create bar plot of scores by group and gender. Give suitable label in the x axis, y axis and a title. Colors of all label should be black and title should be bold. Color of bar plot of men and women scores should be green and red. Data: Scores_men = (22, 30, 35, 35, 26) Scores_women = (25, 32, 30, 35, 29) Subplot 3: Write a Python programming to create a pie chart with a title of the popularity of Car company. Make multiple wedges of the pie. Also show the percentage. data: Car : Maruti Suzuki, Hyundai, Kia, Toyota, Honda Popularity: 25,50,30,20,35 Subplot 4: Write a Python program to draw a scatter plot comparing two subject marks of Mathematics and Science. Use marks of 10 students. Marker of mathematics and science should be circle and star. Colors of marker of mathematics and science should be yellow and blue. Test Data: math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34] science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30] Subplot 5: Write a Python programming to display a horizontal bar chart of the popularity of programming Languages. Colors of all programming Languages should be different. Give suitable label in the x axis, y axis and a title. data: Programming languages: Java, Python, PHP, JavaScript, C, C++ Popularity: 20,100,25,30,45,50 Subplot 6: Write a Python programming to display a Histogram chart for given data. Color of chart should be red. Data=[10,20,20,30,30,30,40,40,40,40,50,50,50,60,60,70]”

import matplotlib.pyplot as plt

# Subplot 1
plt.subplot(3, 2, 1)
x_values = [5, 10, 25, 60, 80]
y_values = [5, 17, 25, 40, 30]
plt.plot(x_values, y_values, color='green', linestyle='dotted', marker='D')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with Dotted Line and Diamond Marker')

# Subplot 2
plt.subplot(3, 2, 2)
Scores_men = (22, 30, 35, 35, 26)
Scores_women = (25, 32, 30, 35, 29)
groups = ['Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5']
# bar_width = 0.35
bar_positions_men = range(len(groups))
bar_positions_women = [pos + bar_width for pos in bar_positions_men]

plt.bar(bar_positions_men, Scores_men, color='green', width=bar_width, label='Men')
plt.bar(bar_positions_women, Scores_women, color='red', width=bar_width, label='Women')
plt.xlabel('Groups')
plt.ylabel('Scores')
plt.title('Bar Plot of Scores by Group and Gender')
# plt.xticks([pos + bar_width / 2 for pos in bar_positions_men], groups)
# plt.legend(fontsize='small')

# Subplot 3
plt.subplot(3, 2, 3)
car_labels = ['Maruti Suzuki', 'Hyundai', 'Kia', 'Toyota', 'Honda']
popularity = [25, 50, 30, 20, 35]
plt.pie(popularity, labels=car_labels, autopct='%1.1f%%', startangle=90)
plt.title('Popularity of Car Companies')

# Subplot 4
plt.subplot(3, 2, 4)
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
plt.scatter(range(1, 11), math_marks, marker='o', color='yellow', label='Mathematics')
plt.scatter(range(1, 11), science_marks, marker='*', color='blue', label='Science')
plt.xlabel('Students')
plt.ylabel('Marks')
plt.title('Scatter Plot: Mathematics vs Science')
# plt.legend(fontsize='small')

# Subplot 5
plt.subplot(3, 2, 5)
languages = ['Java', 'Python', 'PHP', 'JavaScript', 'C', 'C++']
popularity_languages = [20, 100, 25, 30, 45, 50]
plt.barh(languages, popularity_languages, color=['orange', 'green', 'blue', 'red', 'purple', 'pink'])
plt.xlabel('Popularity')
plt.ylabel('Prog Lang')
plt.title('Popularity of Programming Languages')

# Subplot 6
plt.subplot(3, 2, 6)
data_histogram = [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 60, 60, 70]
plt.hist(data_histogram, color='red', bins=10, edgecolor='black')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram Chart')

plt.tight_layout(w_pad=20.0)  # Increase both vertical and horizontal spacing, add rect parameter for title
plt.show()

Get total profit of all months and show line plot with the following Style properties:

• Line Style dotted and Line-color should be red • Show legend at the lower right location. • X label name = Month Number • Y label name = Total Profits • Add a circle marker • Line marker color as blue • Line marker size as 5 • Line width should be 3

import matplotlib.pyplot as plt

# Month Number and Total Profit data
month_numbers = list(range(1, 13))
total_profits = [
    211000, 183300, 224700, 222700,
    209600, 201400, 295500, 361400,
    234000, 266700, 412800, 300200
]

plt.figure(figsize=(10, 5))
plt.plot(month_numbers, total_profits, 
         linestyle='dotted', color='red', marker='o',
         markerfacecolor='blue', markersize=5,
         linewidth=3, label='Total Profits')

plt.xlabel('Month Number')
plt.ylabel('Total Profits')
plt.title('Total Profits of All Months')
plt.legend(loc="lower right")
plt.grid(True)
plt.show()

There is an array of scores of 5 Batsmen in 4 T20 Matches. Which is given below.

Scores=        [[31, 12, 19, 53], 
               [67, 48, 95, 83], 
               [59, 67, 13, 59], 
               [62, 29, 99, 88], 
               [87, 91, 69, 76]]
1. Find the maximum score in T_20-3 and print it (use only the numpy module)
2. Find the minimum score of YUVRAJ and print it (use only the numpy module)
3. Add an extra column with the sum of all 4 T20 Matches’ scores of each batsman in the array created and print it. (use only the numpy module)   

import numpy as np

# Sample scores array
Scores = np.array([[31, 12, 19, 53],
                   [67, 48, 95, 83],
                   [59, 67, 13, 59],
                   [62, 29, 99, 88],
                   [87, 91, 69, 76]])

# 1. Find the maximum score in T_20-3 (index 2)
max_score = Scores[:, 2][0]  # Assume the first batsman has the maximum score initially
for score in Scores[:, 2][1:]:  # Iterate through other scores
    if score > max_score:
        max_score = score

# Find indices where the third column (index 2) is equal to the maximum score
max_score_indices = np.where(Scores[:, 2] == max_score)

# Extract the corresponding rows (batsmen) and scores
max_score_batsmen = Scores[max_score_indices]
max_scores = max_score_batsmen[:, 2]

# Print the maximum score(s) and corresponding batsmen
print("Maximum score in T_20-3:")
for i, score in enumerate(max_scores):
    print(f"- Batsman {i+1}: {score}")

# 2. Find the minimum score of YUVRAJ (assuming YUVRAJ is batsman 3)
yuvraj_score = Scores[2, 2]  # Access score of batsman 3 (index 2) in T_20-3 (index 2)
min_score = yuvraj_score

for score in Scores[:, 2]:  # Iterate through all scores in column 2 (T_20-3)
    if score < min_score:
        min_score = score

print(f"Minimum score of YUVRAJ: {min_score}")

# 3. Add an extra column with the sum of all 4 T20 Matches' scores
import numpy as np

# Sample scores array
Scores = np.array([[31, 12, 19, 53],
                   [67, 48, 95, 83],
                   [59, 67, 13, 59],
                   [62, 29, 99, 88],
                   [87, 91, 69, 76]])



# Calculate the sum of all 4 T20 Matches' scores for each batsman
total_scores = np.zeros(Scores.shape[0])
for i in range(Scores.shape[0]):
    total_score = 0
    for j in range(Scores.shape[1]):
        total_score += Scores[i, j]
    total_scores[i] = total_score

# Create a new array with an extra column using concatenate
new_Scores = np.concatenate((Scores, total_scores[:, np.newaxis]), axis=1)

# Print the scores with the total sum column
print("Scores with total sum column:")
print(new_Scores)

Maximum score in T_20-3:
- Batsman 1: 99
Minimum score of YUVRAJ: 13
Scores with total sum column:
[[ 31.  12.  19.  53. 115.]
 [ 67.  48.  95.  83. 293.]
 [ 59.  67.  13.  59. 198.]
 [ 62.  29.  99.  88. 278.]
 [ 87.  91.  69.  76. 323.]]